package jsoniterx

import (
	jsoniter "github.com/json-iterator/go"
	"github.com/modern-go/reflect2"
	"github.com/shopspring/decimal"
	"time"
	"unsafe"
)

const (
	TimeDefaultFormat = "2006-01-02 15:04:05"
)

func AddJsoniterExtends() {
	// 注册时间默认格式
	jsoniter.RegisterTypeDecoderFunc(reflect2.TypeOf(time.Time{}).String(), func(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
		t, err := time.Parse(TimeDefaultFormat, iter.ReadString())
		if err != nil {
			iter.ReportError("decode time.Time ", err.Error())
			return
		}
		*(*time.Time)(ptr) = t
	})

	jsoniter.RegisterTypeEncoderFunc(reflect2.TypeOf(time.Time{}).String(), func(ptr unsafe.Pointer, stream *jsoniter.Stream) {
		t := *(*time.Time)(ptr)
		stream.WriteString(t.Format(TimeDefaultFormat))
	}, func(ptr unsafe.Pointer) bool {
		t := *(*time.Time)(ptr)
		return t.IsZero()
	})

	// 注册decimal.Decimal类型处理
	jsoniter.RegisterTypeDecoderFunc(reflect2.TypeOf(decimal.Decimal{}).String(), func(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
		t, err := decimal.NewFromString(iter.ReadString())
		if err != nil {
			iter.ReportError("decode decimal.Decimal ", err.Error())
			return
		}
		*(*decimal.Decimal)(ptr) = t
	})

	jsoniter.RegisterTypeEncoderFunc(reflect2.TypeOf(decimal.Decimal{}).String(), func(ptr unsafe.Pointer, stream *jsoniter.Stream) {
		t := *(*decimal.Decimal)(ptr)
		stream.WriteString(t.String())
	}, func(ptr unsafe.Pointer) bool {
		t := *(*decimal.Decimal)(ptr)
		return t.IsZero()
	})

	// 注册time.Time类型扩展，支持用 format标签  指定时间格式
	jsoniter.RegisterExtension(&UpdateStructTimeFieldDescriptorExtension{})
	// 注册 枚举的扩展，标有enum标签的字段转json时候除写入原字段外还写入一个新字段，新字段名称=原字段名称+后缀，供前端显示用
	jsoniter.RegisterExtension(NewUpdateStructEnumFieldDescriptorExtension("_label"))
	// 注册字段打码标签
	jsoniter.RegisterExtension(&UpdateStructMaskFieldDescriptorExtension{})
}
